package com.qzsoft.zhjd.laboratory.modules.groutingRecord.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.platform.security.user.SecurityUser;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.utils.DateUtils;
import com.qzsoft.zhjd.common.utils.ResultUtils;
import com.qzsoft.zhjd.laboratory.modules.groutingRecord.entity.GroutingRecord;
import com.qzsoft.zhjd.laboratory.modules.groutingRecord.mapper.GroutingRecordMapper;
import com.qzsoft.zhjd.laboratory.modules.groutingRecord.service.GroutingRecordService;
import com.qzsoft.zhjd.laboratory.modules.groutingResult.entity.GroutingResult;
import com.qzsoft.zhjd.laboratory.modules.groutingResult.service.GroutingResultService;
import com.qzsoft.zhjd.laboratory.modules.tensionProcess.entity.TensionProcess;
import com.qzsoft.zhjd.laboratory.modules.tensionRecording.entity.TensionRecording;
import com.qzsoft.zhjd.laboratory.modules.tensionResult.entity.TensionResult;
import lombok.AllArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 压浆记录(GroutingRecord)表服务实现类
 *
 * @author makejava
 * @since 2023-07-12 14:59:13
 */
@AllArgsConstructor
@Service("groutingRecordService")
public class GroutingRecordServiceImpl extends ServiceImpl<GroutingRecordMapper, GroutingRecord> implements GroutingRecordService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;
    @Autowired
    private GroutingResultService resultService;

    @Override
    public IPage<GroutingRecord> page(Map<String, Object> params) {
        IPage<GroutingRecord> page = baseServiceComponent.getPage(params, GroutingRecord.class);
        return baseMapper.query(page, params);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @Override
    public GroutingRecord getInfoById(String id) {
        return getById(id);
    }

    /**
     * 新增
     *
     * @param groutingRecord
     */
    @Override
    public void insertGroutingRecord(GroutingRecord groutingRecord) {
        groutingRecord.setId(IdWorker.get32UUID());
        //创建者
        groutingRecord.setCreateBy(SecurityUser.getUserId() == null ? null : SecurityUser.getUserId());
        //创建时间
        groutingRecord.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        save(groutingRecord);
        try{
            groutingDataSend(groutingRecord.getLinkCode());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 修改
     *
     * @param groutingRecord
     */
    @Override
    public void updateGroutingRecord(GroutingRecord groutingRecord) {
        //修改者
        groutingRecord.setUpdateBy(SecurityUser.getUserId() == null ? null : SecurityUser.getUserId());
        //修改时间
        groutingRecord.setUpdateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        updateById(groutingRecord);
    }

    /**
     * 删除
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<String> ids) {
        removeByIds(ids);
    }

    @Override
    @Transactional
    public Result groutingDataReception(JSONObject groutingJson) {
        GroutingRecord groutingRecord = JSONUtil.toBean(groutingJson, GroutingRecord.class);
        QueryWrapper<GroutingRecord> query = new QueryWrapper<>();
        query.eq("code",groutingRecord.getCode());
        query.eq("tensioning_beam_type",groutingRecord.getTensioningBeamType());
        query.eq("beam_number",groutingRecord.getBeamNumber());
        query.eq("pile_number",groutingRecord.getPileNumber());
        query.eq("grout_agent",groutingRecord.getGroutAgent());
        query.eq("cement",groutingRecord.getCement());
        query.eq("borehole_count",groutingRecord.getBoreholeCount());
        query.eq("grouting_direction",groutingRecord.getGroutingDirection());
        query.eq("step_count",groutingRecord.getStepCount());
        query.eq("step_parameters",groutingRecord.getStepParameters());
        query.eq("initial_flow_velocity",groutingRecord.getInitialFlowVelocity());
        query.eq("flowability_s",groutingRecord.getFlowabilityS());
        query.eq("device_number",groutingRecord.getDeviceNumber());
        List<GroutingRecord> grResult = this.list(query);
        if(grResult.size()==0){
            //转换result数据
            JSONArray resultListJson = groutingJson.getJSONArray("resultList");
            List<GroutingResult> resultList =  JSONUtil.toList(resultListJson, GroutingResult.class);
            //自动生成关联ID
            String linkCode = UUID.randomUUID().toString().replace("-","");
            //填充linkCode
            groutingRecord.setLinkCode(linkCode);
            if(resultList!=null){
                resultList.stream().forEach(result -> {
                    result.setId(IdWorker.get32UUID());
                    //创建者
                    result.setCreateBy(SecurityUser.getUserId());
                    //创建时间
                    result.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
                    result.setLinkCode(linkCode);
                });
                //数据插入处理
                this.insertGroutingRecord(groutingRecord);
                resultService.saveBatch(resultList);
            }else{
                return ResultUtils.error("resultList不可为空值!");
            }
            //进行linkCode码推送
//            try{
//                groutingDataSend(groutingRecord.getLinkCode());
//            } catch (Exception e){
//                e.printStackTrace();
//            }
        }else{
            return ResultUtils.error("该数据已存在!");
        }
        return ResultUtils.ok();
    }

    private void groutingDataSend(String linkCode) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://111.14.222.59:9163/prod-api/zhgd/nLaboratoryGroutingRequires/isQualified?linkCode="+linkCode);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            // 对得到后的实例可以进行处理，例如读取回复体，读取html
            HttpEntity entity = response.getEntity();
            System.out.println(new Date());
            System.out.println("=======================");
            String html = EntityUtils.toString(entity);
            System.out.println(html);
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
        // 6. 释放连接
        response.close();
        httpClient.close();
    }
}

